package com.yzd.learnjava.concurrency;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

import com.yzd.learnjava.util.Print;

public class AttemptLocking {
	private ReentrantLock lock = new ReentrantLock();
	public void untimed(){
		boolean captured = lock.tryLock();
		try {
			Print.print("tryLock():" + captured);
		} finally {
			if(captured) {
				lock.unlock();
			}
		}
	}
	
	public void timed() {
		boolean captured = false ;
		try {
			captured = lock.tryLock(2, TimeUnit.SECONDS);
		} catch(InterruptedException e) {
			e.printStackTrace();
		}
		
		try{
			Print.print("tryLock(2, TimeUnits.SECONDS):" + captured);
		}finally {
			if(captured) {
				lock.unlock();
			}
		}
	}
	
	public static void main(String[] args) throws InterruptedException {
		final AttemptLocking al = new AttemptLocking();
		al.untimed();
		al.timed();
		new Thread() {
			{setDaemon(true);}
			
			public void run() {
				al.lock.lock();
				Print.print("Acquired");
			}
		}.start();
		
		//Thread.yield();
		TimeUnit.MILLISECONDS.sleep(10);
		al.untimed();
		al.timed();
	}
}
